package com.woniuxy.opencv.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static com.woniuxy.common.constant.FinanceConstant.User.TOKEN;


/*
 * @Auther:吴兴龙
 * @Date:2023/2/13
 * @Description:
 */
@Configuration
public class FeignConfig implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {

        // token
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader(TOKEN);
        // 如果没有token，就从session中获取
        if (token == null) {
            HttpSession session = request.getSession(false);
            if (session != null) {
                token = (String) session.getAttribute(TOKEN);
            }
        }

        // 把token放到feign请求头中
        requestTemplate.header(TOKEN, token);
    }
}
